package com.peng.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

    @GetMapping({"/", "/index"})
    public String index() {
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/toMain")
    public String toMain() {
        return "main";
    }

    @RequestMapping("/failure")
    public String tofailure(Model model) {
        model.addAttribute("loginFail", "T");
        return "login";
    }

    @RequestMapping("/403")
    public String to403() {
        return "403";
    }

    @Secured(value = "ROLE_管理员")
    @RequestMapping("/admin/read")
    @ResponseBody
    public String adminread() {
        return "管理员读权限";
    }

    @Secured(value = "ROLE_管理员")
    @RequestMapping("/admin/write")
    @ResponseBody
    public String adminwrite() {
        return "管理员写权限";
    }

    @Secured({"ROLE_游客", "ROLE_管理员"})
    @RequestMapping("/guest/read")
    @ResponseBody
    public String guestRead() {
        return "游客写去那先";
    }

    @Secured({"ROLE_游客", "ROLE_管理员"})
    @RequestMapping("/guest/write")
    @ResponseBody
    public String guestWrite() {
        return "游客写权限";
    }

    @RequestMapping("/all/toMain")
    @ResponseBody
    public String AllMain() {
        return "所有人主页";
    }

    @RequestMapping("/all/error")
    @ResponseBody
    public String error() {
        return "错误页面";
    }

    /**
     * PreAuthorize - 方法执行前，校验权限是否满足
     * PostAuthorize - 方法执行结束后，校验权限是否满足。
     *
     * @return
     */
    @RequestMapping("/all/write")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority({'admin:write','guest:write'})")
    public String allWrite() {
        return "所有用户写操作";
    }

    @RequestMapping("/all/read")
    @ResponseBody
    @PreAuthorize("hasAnyAuthority({'admin:read','guest:read'})")
    public String allRead() {
        return "所有用户读操作";
    }
}
